"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileContain = exports.logError = exports.logInfo = exports.send = exports.exec = exports.date = exports.compareVersion = exports.readfile = exports.isExist = exports.tempDir = void 0;
const tslib_1 = require("tslib");
const fs_1 = require("fs");
const cp = tslib_1.__importStar(require("child_process"));
const path = tslib_1.__importStar(require("path"));
const os = tslib_1.__importStar(require("os"));
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const line_reader_1 = tslib_1.__importDefault(require("line-reader"));
/**
 * 创建并返回存放文件的临时目录
 */
async function tempDir() {
    const dir = path.join(os.homedir(), '.tagup');
    if (!await isExist(dir, true)) {
        await fs_1.promises.mkdir(dir);
    }
    return dir;
}
exports.tempDir = tempDir;
/**
 * 判断路径是否存在
 * @param path 文件或文件夹路径
 * @param isDir 是否是文件夹，默认为文件
 */
async function isExist(path, isDir = false) {
    try {
        const stat = await fs_1.promises.stat(path);
        if (isDir)
            return stat.isDirectory();
        return true;
    }
    catch (err) {
        return false;
    }
}
exports.isExist = isExist;
/**
 * 读取文件内容
 * @param filepath 文件路径
 */
async function readfile(filepath) {
    if (await isExist(filepath)) {
        return await fs_1.promises.readFile(filepath, 'utf-8');
    }
    return null;
}
exports.readfile = readfile;
/**
 * a >= b
 */
function compareVersion(a = '0.0.0', b = '0.0.0') {
    a = a.replace(/[^\d.]/, '');
    b = b.replace(/[^\d.]/, '');
    if (a === b)
        return true;
    const A = a.split('.').map(Number);
    const B = b.split('.').map(Number);
    for (let len = Math.max(A.length, B.length) - 1; len >= 0; len--) {
        const a1 = A[len] || 0;
        const b1 = B[len] || 0;
        if (a1 > b1)
            return true;
    }
    return false;
}
exports.compareVersion = compareVersion;
function date(format = 'YYYY/MM/DD HH:mm:ss') {
    const d = new Date();
    function padLeft(val) {
        return String(val).padStart(2, '0');
    }
    const Y = d.getFullYear();
    const M = d.getMonth() + 1;
    const D = d.getDate();
    const H = d.getHours();
    const m = d.getMinutes();
    const s = d.getSeconds();
    return format
        .replace(/Y+/, String(Y))
        .replace(/M{2}/g, padLeft(M))
        .replace(/M/g, String(M))
        .replace(/D{2}/g, padLeft(D))
        .replace(/D/g, String(D))
        .replace(/H{2}/g, padLeft(H))
        .replace(/H/g, String(H))
        .replace(/m{2}/g, padLeft(m))
        .replace(/m/g, String(m))
        .replace(/s{2}/g, padLeft(s))
        .replace(/s/g, String(s));
}
exports.date = date;
exports.exec = (cmd, options = {}) => {
    return new Promise((resolve, reject) => {
        cp.exec(cmd, Object.assign({ timeout: 60 * 1000 }, options), (err, stdout, stderr) => {
            if (err)
                return reject(err);
            resolve({ stdout, stderr });
        });
    });
};
function send(message, type = true) {
    const { REPO_NAME, TAG } = process.env;
    message !== null && process.send && process.send({ message, type, repoName: REPO_NAME, tag: TAG });
}
exports.send = send;
/**
 * 写入日志，并打印到终端
 */
async function log(type, repoName = '', tag = '', content) {
    if (typeof content === 'string')
        content = content.trim();
    if (content === '')
        return;
    const logPath = path.join(await tempDir(), `${repoName}-${date('YYYYMMDD')}-${type}.log`);
    const dt = date();
    console.log(chalk_1.default.blue(repoName), `[${chalk_1.default.grey(tag)}]:`, dt);
    console.log(type === 'error' ? chalk_1.default.red(content) : content, '\n');
    await fs_1.promises.appendFile(logPath, `${repoName} [${tag}]: ${date()}\n${content}\n\n`, 'utf8');
}
async function logInfo(repoName = '', tag = '', content) {
    await log('out', repoName, tag, content);
}
exports.logInfo = logInfo;
async function logError(repoName = '', tag = '', content) {
    if (Object.prototype.toString.call(content) === '[object Object]') {
        content = JSON.stringify(content);
    }
    await log('error', repoName, tag, content);
}
exports.logError = logError;
/**
 * 判断known_hosts文件中是否含有domain
 */
async function fileContain(domain) {
    const kh = path.join(os.homedir(), '.ssh/known_hosts');
    const exist = await isExist(kh);
    return new Promise((resolve) => {
        if (exist) {
            line_reader_1.default.eachLine(kh, (line, last) => {
                if (line.indexOf(`${domain} ssh-rsa `) > -1) {
                    resolve(true);
                    return false;
                }
                if (last)
                    resolve(false);
            });
        }
        else {
            resolve(false);
        }
    });
}
exports.fileContain = fileContain;
